package com.atguigu.tingshu.cdc.config;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;

/**
 * ClassName: CdcCanalConfiguration
 * Package: com.atguigu.tingshu.cdc.config
 * Description:
 *
 * @Author 梅超凡
 * @Create 2025/2/13 10:53
 * @Version 1.0
 */
@Slf4j
@Configuration
public class CdcCanalConfiguration {

    // 从配置文件中读取 Canal 服务器地址
    @Value("${canal.server}")
    private String canalServer;

    // 从配置文件中读取 Canal 目标名称
    @Value("${canal.destination}")
    private String canalDestination;


    /**
     * 初始化方法，用于建立与 Canal 服务器的连接
     */
    @Bean
    public CanalConnector canalConnector() {
        log.info("canalServer:{}", canalServer);
        String[] serverParts = canalServer.split(":");
        if (serverParts.length != 2) {
            throw new IllegalArgumentException("无效的canal服务器配置: " + canalServer);
        }
        String canalServerIp = serverParts[0];
        int canalServerPort = Integer.parseInt(serverParts[1]);
        InetSocketAddress inetSocketAddress = new InetSocketAddress(canalServerIp, canalServerPort);
        CanalConnector canalConnector = CanalConnectors.newSingleConnector(inetSocketAddress, canalDestination, "", "");
        // 记录日志，表示 Canal 连接已建立并开始监听 binlog 事件
        log.info("Canal 连接已建立，开始监听 binlog 事件");
        return canalConnector;
    }


}
